﻿using System;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using MS.InformationManagement.DAL.Support;
using support = MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using DAL = MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Core.Documentset;
using Office = Microsoft.Office.DocumentManagement.DocumentSets;
using System.Data;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.RecordCenter;
using MS.InformationManagement.Core.RecordSiteQuery;
using MS.InformationManagement.Core.TransactionsResponse;

namespace MS.InformationManagement.Core.TomoActions
{
    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class TomoActions
    {
        public Tomo CurrentVolumeEntity { get; set; }

        public Tomo getVolumeIfExists(string expedId)
        {
            Tomo founded = default(Tomo);
            Guid siteID = SPContext.Current.Site.ID;
            string query = string.Format("<Where><Eq><FieldRef Name='Expediente_Id' /><Value Type='Text'>{0}</Value></Eq></Where><OrderBy><FieldRef Name='Volume_Initial_Date' Ascending='False' /></OrderBy>",
                expedId);
            SPQuery spQuery = new SPQuery { Query = query };

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite overridenSite = new SPSite(siteID))
                {
                    using (SPWeb overridenWeb = overridenSite.OpenWeb())
                    {
                        SPList targetList = overridenWeb.Lists.TryGetList(GlobalConstants.LIST_TOMOS);
                        if (targetList == null) { throw new Exception("La lista de tomos no existe"); }
                        SPListItemCollection foundElements = targetList.GetItems(spQuery);
                        if (foundElements.Count == 0)
                        {
                            CreateVolume(true, 0, expedId, overridenWeb);
                            founded = CurrentVolumeEntity;
                        }
                        else
                        {
                            SPListItem firstElement = foundElements[0];
                            founded = GetTomo(firstElement);
                        }
                    }
                }
            });

            return founded;
        }

        public Tomo getVolumeIfExists(string expedId, SPWeb web)
        {
            Tomo founded = default(Tomo);
            string query = string.Format("<Where><Eq><FieldRef Name='Expediente_Id' /><Value Type='Text'>{0}</Value></Eq></Where><OrderBy><FieldRef Name='Volume_Initial_Date' Ascending='False' /></OrderBy>",
                expedId);
            SPQuery spQuery = new SPQuery { Query = query };

            SPList targetList = web.Lists.TryGetList(GlobalConstants.LIST_TOMOS);
            if (targetList == null) { throw new Exception("La lista de tomos no existe"); }
            SPListItemCollection foundElements = targetList.GetItems(spQuery);
            if (foundElements.Count == 0)
            {
                CreateVolume(true, 0, expedId, web);
                founded = CurrentVolumeEntity;
            }
            else
            {
                SPListItem firstElement = foundElements[0];
                founded = GetTomo(firstElement);
            }

            return founded;
        }

        private Tomo GetTomo(SPListItem spListItem)
        {
            return new Tomo
            {
                Caja = spListItem[CustomSiteColumns.FIELD_VOLUME_BOX] == null ? string.Empty : spListItem[CustomSiteColumns.FIELD_VOLUME_BOX].ToString(),
                Cara = spListItem[CustomSiteColumns.FIELD_VOLUME_SIDE] == null ? string.Empty : spListItem[CustomSiteColumns.FIELD_VOLUME_SIDE].ToString(),
                Carpeta = spListItem[CustomSiteColumns.FIELD_VOLUME_FOLDER] == null ? string.Empty : spListItem[CustomSiteColumns.FIELD_VOLUME_FOLDER].ToString(),
                Entrepaño = spListItem[CustomSiteColumns.FIELD_VOLUME_PANEL] == null ? string.Empty : spListItem[CustomSiteColumns.FIELD_VOLUME_PANEL].ToString(),
                Estante = spListItem[CustomSiteColumns.FIELD_VOLUME_SHELF] == null ? string.Empty : spListItem[CustomSiteColumns.FIELD_VOLUME_SHELF].ToString(),
                FechaFinal = spListItem[CustomSiteColumns.FIELD_VOLUME_FINAL_DATE] == null ? new Nullable<DateTime>()
                    : Convert.ToDateTime(spListItem[CustomSiteColumns.FIELD_VOLUME_FINAL_DATE]),
                FechaInicial = spListItem[CustomSiteColumns.FIELD_VOLUME_INITIAL_DATE] == null ? new Nullable<DateTime>()
                    : Convert.ToDateTime(spListItem[CustomSiteColumns.FIELD_VOLUME_INITIAL_DATE]),
                Id = spListItem.ID,
                NúmeroExpediente = spListItem[CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID] == null ? string.Empty : spListItem[CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID].ToString(),
                Piso = spListItem[CustomSiteColumns.FIELD_VOLUME_FLOOR] == null ? string.Empty : spListItem[CustomSiteColumns.FIELD_VOLUME_FLOOR].ToString(),
                Title = spListItem.Title
            };
        }

        public void CreateVolume(bool isNew, int idLastVolume, string expedId, SPWeb web)
        {
            SPList userList = web.Lists.TryGetList(GlobalConstants.LIST_TOMOS);
            if (userList == null)
                throw new Exception(string.Format(ExceptionConstants.ERROR_BIBLIOTECA_USUARIO_INEXISTENTE, GlobalConstants.LIST_TOMOS));

            web.AllowUnsafeUpdates = true;
            SPListItem newItem = userList.Items.Add();

            newItem[SPBuiltInFieldId.Title] = isNew ? "1" : (idLastVolume + 1).ToString();
            newItem[CustomSiteColumns.FIELD_VOLUME_INITIAL_DATE] = isNew ? DateTime.Now : CurrentVolumeEntity.FechaInicial;
            newItem[CustomSiteColumns.FIELD_VOLUME_FINAL_DATE] = DateTime.Now;

            if (CurrentVolumeEntity != null)
            {
                newItem[CustomSiteColumns.FIELD_VOLUME_BOX] = CurrentVolumeEntity.Caja;
                newItem[CustomSiteColumns.FIELD_VOLUME_FLOOR] = CurrentVolumeEntity.Piso;
                newItem[CustomSiteColumns.FIELD_VOLUME_FOLDER] = CurrentVolumeEntity.Carpeta;
                newItem[CustomSiteColumns.FIELD_VOLUME_PANEL] = CurrentVolumeEntity.Entrepaño;
                newItem[CustomSiteColumns.FIELD_VOLUME_SHELF] = CurrentVolumeEntity.Estante;
                newItem[CustomSiteColumns.FIELD_VOLUME_SIDE] = CurrentVolumeEntity.Cara;
            }

            newItem[CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID] = expedId;
            newItem.Update();

            web.AllowUnsafeUpdates = false;

            if (CurrentVolumeEntity == null)
            {
                CurrentVolumeEntity = new Tomo();
                CurrentVolumeEntity.Id = newItem.ID;
            }
        }

        public void CreateVolume(bool isNew, int idLastVolume, string expedId)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
             {
                 using (SPSite ElevatedsiteColl = new SPSite(SPContext.Current.Site.ID))
                 {
                     using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb())
                     {

                         SPList userList = ElevatedSite.Lists.TryGetList(GlobalConstants.LIST_TOMOS);
                         if (userList == null)
                             throw new Exception(string.Format(ExceptionConstants.ERROR_BIBLIOTECA_USUARIO_INEXISTENTE, GlobalConstants.LIST_TOMOS));

                         SPContext.Current.Web.AllowUnsafeUpdates = true;
                         SPListItem newItem = userList.Items.Add();

                         newItem[SPBuiltInFieldId.Title] = isNew ? "1" : (idLastVolume + 1).ToString();
                         newItem[CustomSiteColumns.FIELD_VOLUME_INITIAL_DATE] = isNew ? DateTime.Now : CurrentVolumeEntity.FechaInicial;
                         newItem[CustomSiteColumns.FIELD_VOLUME_FINAL_DATE] = DateTime.Now;

                         if (CurrentVolumeEntity != null)
                         {
                             newItem[CustomSiteColumns.FIELD_VOLUME_BOX] = CurrentVolumeEntity.Caja;
                             newItem[CustomSiteColumns.FIELD_VOLUME_FLOOR] = CurrentVolumeEntity.Piso;
                             newItem[CustomSiteColumns.FIELD_VOLUME_FOLDER] = CurrentVolumeEntity.Carpeta;
                             newItem[CustomSiteColumns.FIELD_VOLUME_PANEL] = CurrentVolumeEntity.Entrepaño;
                             newItem[CustomSiteColumns.FIELD_VOLUME_SHELF] = CurrentVolumeEntity.Estante;
                             newItem[CustomSiteColumns.FIELD_VOLUME_SIDE] = CurrentVolumeEntity.Cara;
                         }

                         newItem[CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID] = expedId;
                         newItem.Update();

                         SPContext.Current.Web.AllowUnsafeUpdates = false;

                         if (CurrentVolumeEntity == null)
                         {
                             CurrentVolumeEntity = new Tomo();
                             CurrentVolumeEntity.Id = newItem.ID;
                         }
                     }
                 }
             });
        }

        public void UpdateVolume(int idVolumen)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedsiteColl = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb())
                    {
                        SPList userList = ElevatedSite.Lists.TryGetList(GlobalConstants.LIST_TOMOS);
                        if (userList == null)
                            throw new Exception(string.Format(ExceptionConstants.ERROR_BIBLIOTECA_USUARIO_INEXISTENTE, GlobalConstants.LIST_TOMOS));

                        ElevatedSite.AllowUnsafeUpdates = true;
                        SPListItem newItem = userList.GetItemById(idVolumen);

                        newItem[CustomSiteColumns.FIELD_VOLUME_FINAL_DATE] = DateTime.Now;
                        newItem[CustomSiteColumns.FIELD_VOLUME_BOX] = CurrentVolumeEntity.Caja;
                        newItem[CustomSiteColumns.FIELD_VOLUME_FLOOR] = CurrentVolumeEntity.Piso;
                        newItem[CustomSiteColumns.FIELD_VOLUME_PANEL] = CurrentVolumeEntity.Entrepaño;
                        newItem[CustomSiteColumns.FIELD_VOLUME_SHELF] = CurrentVolumeEntity.Estante;
                        newItem[CustomSiteColumns.FIELD_VOLUME_SIDE] = CurrentVolumeEntity.Cara;
                        newItem.Update();

                        ElevatedSite.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

        public void UpdateDateInVolume(int idVolumen)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite overridenSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb overridenWeb = overridenSite.OpenWeb())
                    {
                        SPList userList = overridenWeb.Lists.TryGetList(GlobalConstants.LIST_TOMOS);
                        if (userList == null)
                            throw new Exception(string.Format(ExceptionConstants.ERROR_BIBLIOTECA_USUARIO_INEXISTENTE, GlobalConstants.LIST_TOMOS));

                        overridenWeb.AllowUnsafeUpdates = true;
                        SPListItem newItem = userList.GetItemById(idVolumen);

                        newItem[CustomSiteColumns.FIELD_VOLUME_FINAL_DATE] = DateTime.Now;
                        newItem.Update();

                        overridenWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

        public void UpdateDateInVolume(int idVolumen, SPWeb web)
        {
            SPList userList = web.Lists.TryGetList(GlobalConstants.LIST_TOMOS);
            if (userList == null)
                throw new Exception(string.Format(ExceptionConstants.ERROR_BIBLIOTECA_USUARIO_INEXISTENTE, GlobalConstants.LIST_TOMOS));

            web.AllowUnsafeUpdates = true;
            SPListItem newItem = userList.GetItemById(idVolumen);

            newItem[CustomSiteColumns.FIELD_VOLUME_FINAL_DATE] = DateTime.Now;
            newItem.Update();

            web.AllowUnsafeUpdates = false;
        }
    }
}
